<?php
namespace app\home\controller;
use app\common\controller\AuthBase;
use app\home\model\Authgroup as GroupModel;
use app\home\model\AuthGroupAccess;
use app\home\model\Authrule;
use think\Db;
use think\Request;
use app\common\controller\Backend;
/**
 * @title 角色管理
 * @description 接口说明
 * @group AUTH权限
 */
class Authgroup extends AuthBase{

    function _initialize(){
        parent::_initialize();
        $this->model = new \app\home\model\Authgroup();
    }
    public function getlist(){
        $page = (int)input('page', 1);
        $limit = (int)input('limit', 10);
        $map["deleted"] = 0;
        $result = GroupModel::where($map)->order("id asc")->paginate(['page' => $page,'list_rows' => $limit,], false)->toArray();
        $data["status"] = "success";
        $data["totals"] = $result['total'];
        $data["data"] = $result['data'];
        return json($data);
    }

    public function getuser(){
        $page = (int)input('page', 1);
        $limit = (int)input('limit', 10);
        $map["deleted"] = 0;
        $map["status"] = 1;
        $result = GroupModel::where($map)->order("id asc")->select();
        $data["status"] = "success";
        $data["data"] = $result;
        return json($data);
    }

    public function add(){
        if ($this->request->isPost()){
            $param = input("post.");

            $db = new GroupModel();
            $param['creator'] = USER_ID;
            $param['rules'] = implode(',',$param['rules']);

            $res = $db->where('title',$param['title'])->where('deleted',0)->find();
            if ($res) {
                return json(['msg'=>'角色名称已存在','code'=>1]);
            }
            $group_id = $db->insertGetId($param);

            if ($group_id > 0) {
                return json(['msg'=>'操作成功','code'=>0]);
            }else{
                return json(['msg'=>'操作失败','code'=>1]);
            }
        }
    }

    public function edit($id=0){
        $db = new GroupModel();
        //$db = D("Group",'Model');
        if ($this->request->isPost()){
            $param = input();
            //$userid = $param['uid'];

            $id = input("post.group_id");
            unset($param["group_id"],$param['uid']);

            $param['rules'] = implode(',',$param['rules']);
            $param['creator'] = USER_ID;
            $result = $db->allowField(true)->save($param,['id'=>$id]);
            //Db::name("auth_group_access")->where("group_id",$id)->delete();
            /*foreach ($userid as $k => $v){
                if(is_numeric($v)){
                    $aga[$k]["uid"] = $v;
                    $aga[$k]["group_id"] = $id;
                }
            }*/
            /*if(isset($aga)){
                $aga = array_values($aga);
            }*/
            //Db::name("auth_group_access")->insertAll($aga);
            return json(['msg'=>'操作成功','code'=>0]);
        }else{
            $group = Db::name("auth_group")->where(array("id"=>$id,'status'=>1))->find();

            $this->assign("group",$group);
            return view();
        }
    }


    public function del($id=0){
        $id = input("post.group_id");
        if ($id){
            $result = Db::name('auth_group')->where("id",$id)->update(array("deleted"=>1));
            if($result){
                Db::name('auth_group_access')->where("group_id",$id)->delete();
                return json(['msg'=>'操作成功','code'=>0]);
                //$this->success('删除成功');
            }else{
                return json(['msg'=>'操作失败','code'=>0]);
                //$this->error('删除失败');
            }
        }
    }

    /*获取权限结点*/
    public function getnode(){
        $id = input("get.id");

        $map = "status = 1 and isshow = 1 ";
        $data = Db::name("auth_rule")
//            ->field("id,fid as pid,'true'as open,title as name,sort,name as cname,vip")
            ->field("id,fid as pid,'true'as open,title as name,sort,name as cname")
            ->where($map)
            ->order('sort asc')
            ->select();
//        echo M() -> getLastSql();exit;

        $rule = Db::name("auth_group")->where(array("id"=>$id,'status'=>1))->value("rules");

        $rule_array = explode(",",$rule);

//        $member_has_rules = $this->_getHasRule(); //获取会员所有开通的非免费权限数组（ruleid array）
        $new_rule = array();
        foreach($data as $key=>$val){
//		    if( $val['vip'] &&  !in_array($val['id'],$member_has_rules)) unset($data[$key]);
            //判断是否有旧版会一汇帐号,如果有旧版帐号就隐藏会一汇
            //if($member['hasheh'] && strpos($val['cname'],'Heh') !== false) continue;
            if(in_array($val["id"],$rule_array)) $val["checked"] = true;
            $new_rule[] = $val;
        }
        //$this->ajaxReturn($new_rule);
        //return json($new_rule);
        //return ['id'=>1,'title'=>'lsji'];

        return json(['code' => 1, 'rules' => $new_rule]);
    }

    //获取人员
    public function getuserlist(){
        $groupid = input('groupid');

        $field = "u.id,u.name,GROUP_CONCAT(DISTINCT a.group_id) as group_ids";
        $user = new \app\common\model\User();
        $user_list = $user->get_user_group($groupid,$field);

        $ruleStr = Db::name('auth_group')->where('id',$groupid)->value('rules');
        $rulesId = explode(',',$ruleStr);
        $ruleModel = new Authrule();
        $rules = $ruleModel->where('id','in',$rulesId)->field('id,fid')->where('status',1)->select()->toArray();
        $rulesList = $this->tree($rules,'id','fid');

        return json(['msg'=>'操作成功','code'=>0,'data'=>$user_list,'list'=>$rulesList]);
    }

    //禁用 || 启用
    public function enable(){
        $params = input();
        $id = !empty($params['id']) ? $params['id'] : '';
        $status = !empty($params['status']) ? $params['status'] : 0;

        if(!$id){
            return json(['msg'=>'参数错误','code'=>1]);
        }
        $map = ['id' => $id];
        $save = $this->model->where($map)->update(['status' => $status]);

        if($save !== false){
            return json(['msg'=>'操作成功','code'=>0]);
        }else{
            return json(['msg'=>'操作失败','code'=>1]);
        }
    }

}